const { validationResult } = require('express-validator');
const UserService = require('../services/user.service');

class UserController {
  /**
   * 创建新用户
   */
  static async handleCreateUser(req, res, next) {
    try {
      // 验证请求参数
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            message: '请求参数验证失败',
            details: errors.array()
          }
        });
      }

      const userData = req.body;
      const newUser = await UserService.createUser(userData);

      res.status(201).json({
        success: true,
        message: '用户创建成功',
        data: newUser
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 用户登录
   */
  static async handleLogin(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            message: '请求参数验证失败',
            details: errors.array()
          }
        });
      }

      const { username, password } = req.body;
      const loginResult = await UserService.loginUser(username, password);

      res.status(200).json({
        success: true,
        message: '登录成功',
        data: loginResult
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 获取所有用户
   */
  static async handleGetAllUsers(req, res, next) {
    try {
      const filters = {
        page: parseInt(req.query.page) || 1,
        limit: parseInt(req.query.limit) || 10,
        role: req.query.role,
        department: req.query.department,
        search: req.query.search
      };

      const result = await UserService.getAllUsers(filters);

      res.status(200).json({
        success: true,
        message: '获取用户列表成功',
        data: result
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 根据ID获取用户
   */
  static async handleGetUserById(req, res, next) {
    try {
      const { id } = req.params;
      
      if (!id || isNaN(parseInt(id))) {
        return res.status(400).json({
          success: false,
          error: {
            message: '无效的用户ID'
          }
        });
      }

      const user = await UserService.findUserById(parseInt(id));

      res.status(200).json({
        success: true,
        message: '获取用户信息成功',
        data: user
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 更新用户信息
   */
  static async handleUpdateUser(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            message: '请求参数验证失败',
            details: errors.array()
          }
        });
      }

      const { id } = req.params;
      
      if (!id || isNaN(parseInt(id))) {
        return res.status(400).json({
          success: false,
          error: {
            message: '无效的用户ID'
          }
        });
      }

      const updateData = req.body;
      const updatedUser = await UserService.updateUser(parseInt(id), updateData);

      res.status(200).json({
        success: true,
        message: '用户信息更新成功',
        data: updatedUser
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 删除用户
   */
  static async handleDeleteUser(req, res, next) {
    try {
      const { id } = req.params;
      
      if (!id || isNaN(parseInt(id))) {
        return res.status(400).json({
          success: false,
          error: {
            message: '无效的用户ID'
          }
        });
      }

      await UserService.deleteUser(parseInt(id));

      res.status(200).json({
        success: true,
        message: '用户删除成功'
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 修改密码
   */
  static async handleChangePassword(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            message: '请求参数验证失败',
            details: errors.array()
          }
        });
      }

      const { oldPassword, newPassword } = req.body;
      const userId = req.user.userId; // 从JWT中获取用户ID

      await UserService.changePassword(userId, oldPassword, newPassword);

      res.status(200).json({
        success: true,
        message: '密码修改成功'
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 获取当前用户信息
   */
  static async handleGetCurrentUser(req, res, next) {
    try {
      const userId = req.user.userId; // 从JWT中获取用户ID
      const user = await UserService.findUserById(userId);

      res.status(200).json({
        success: true,
        message: '获取当前用户信息成功',
        data: user
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = UserController;